package com.hxht.storage.server.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;

import com.hxht.storage.server.dao.NvrIpchannelDao;
import com.hxht.storage.server.pojo.NvrIpchannelInfo;

@Repository
public class NvrIpchannelDaoImpl extends BaseDaoImpl<NvrIpchannelInfo>
								 implements NvrIpchannelDao{

	@PostConstruct
	public void init(){
		clazz = NvrIpchannelInfo.class;
	}

	@Override
	/**
	 * 返回 dvr状态为online,并且ip通道状态为ilde的 可用通道
	 */
	public List<NvrIpchannelInfo> findIdleIpchannelList() {
		// TODO Auto-generated method stub
		List<NvrIpchannelInfo> ipchannelList = new ArrayList<NvrIpchannelInfo>();
		
		TypedQuery<NvrIpchannelInfo> query = entityManage.createQuery(
				"select ipchannel from NvrIpchannelInfo as ipchannel left join ipchannel.nvrDevice as nvr where nvr.isOnline=:isOnline and ipchannel.isIdle=:idle", clazz)
				.setParameter("idle", true).setParameter("isOnline", true);
		
		ipchannelList = query.getResultList();
		return ipchannelList;
	}

	@Override
	/**
	 * 根据 nvr Ip地址 和 ip通道号，找到对应的DvrIpchannelInfo
	 */
	public NvrIpchannelInfo findByNvrChannel(String nvrIp, int dvrChannel) {
		
		NvrIpchannelInfo ipchannel = null;
		
		TypedQuery<NvrIpchannelInfo> query = entityManage.createQuery(
				"select ipchannel from NvrIpchannelInfo as ipchannel left join ipchannel.nvrDevice as nvr where nvr.ip=:ip and ipchannel.dvrChannel=:channel", clazz)
				.setParameter("ip", nvrIp).setParameter("channel", dvrChannel);
		
		List<NvrIpchannelInfo> ipchannelList = query.getResultList();
		if (ipchannelList != null && ipchannelList.size() != 0){
			ipchannel = ipchannelList.get(0);
		}
		
		return ipchannel;
	}
	
	
	@Override
//	@Transactional(value="nvmpJpaEM", propagation=Propagation.REQUIRED)
	public void insert(NvrIpchannelInfo ipchannel){
		entityManage.persist(ipchannel);
	}

	@Override
	public List<NvrIpchannelInfo> findByNvr(String nvrIp) {
		List<NvrIpchannelInfo> ipchannelList;
		
		TypedQuery<NvrIpchannelInfo> query = entityManage.createQuery(
				"select ipchannel from NvrIpchannelInfo as ipchannel left join ipchannel.nvrDevice as nvr where nvr.ip=:ip", clazz)
				.setParameter("ip", nvrIp);
		ipchannelList = query.getResultList();
		
		return ipchannelList;
	}
}
